<template>
  <div class="carouse-item" ref="root">
    <slot></slot>
  </div>
</template>

<script>
import {defineComponent} from 'vue';

export default defineComponent({
  name: 'CarouselItem',
  props: {
    numInGroup: {
      type: Number,
      default: 3,
      required: true,
      validator(value) {
        return value > 0;
      }
    },
    // 水平方向间隙
    gapX: {
      type: Number,
      default: 12
    },
    // 垂直方向间隙
    gapY: {
      type: Number,
      default: 12
    },
  },
  data() {
    return {
      translateX: 0,
      translateY: 0,
    };
  },
  mounted() {
    const el = this.$refs.root.parentElement;

    // 水平方向元素个数
    const containerWidth = el.offsetWidth;
    const itemWidth = el.firstElementChild.offsetWidth;
    const elCountX = Math.round(containerWidth / (itemWidth + this.gapX));

    // 垂直方向元素个数
    const containerHeight = el.offsetHeight;
    const itemHeight = el.firstElementChild.offsetHeight;
    const elCountY = Math.round(containerHeight / (itemHeight + this.gapY));

    // 水平方向移动距离
    const countX = Math.ceil(this.numInGroup / elCountY)
    const distanceX = (itemWidth + this.gapX) * countX;
    this.translateX = `translateX(-${distanceX}px)`;

    // 垂直方向移动距离
    const countY = Math.ceil(this.numInGroup / elCountX)
    const distanceY = (itemHeight + this.gapY) * countY;
    this.translateY = `translateY(-${distanceY}px)`;
  }
});
</script>

<style scoped>
@keyframes slide-top {
  from {
    transform: translateY(0);
  }
  to {
    transform: v-bind(translateY);
  }
}

.item-move-top {
  -webkit-animation: slide-top 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;
  animation: slide-top 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;
}

@keyframes slide-left {
  from {
    transform: translateX(0);
  }
  to {
    transform: v-bind(translateX);
  }
}

.item-move-left {
  -webkit-animation: slide-left 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;
  animation: slide-left 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;
}
</style>